#!/bin/bash

blackarch=$(dirname "$0")/..
chroot=$HOME/alt/blackarch
image=$HOME/alt/blackarch
nbd=/dev/nbd1
arch=x86_64

base_packages=(base base-devel namcap zsh tmux sudo vim parallel moreutils)

if [[ $UID != 0 ]] ; then
	echo >&2 'must be root'
	exit 1
fi

clear_mounts() {
	cd /

	echo "mounts: ${mounts[@]}"

	for mount in "${mounts[@]}" ; do
		echo "unmounting $mount..."
		umount "$mount"
	done

	mounts=()

	qemu-nbd -d "$nbd"
}
trap clear_mounts EXIT

track_mount() {
	#if mountpoint -q "$2" ; then
	#    echo >&2 "already mountpoint: $2"
	#    exit 1
	#fi

	mounts=("$2" "${mounts[@]}")
	mkdir -p "$2"
	mount "$@"

	echo "mounts now: ${mounts[@]}"
}

connect_nbd() {
	modprobe nbd max_part=63 || true
	qemu-nbd -f qcow2 -c "$nbd" "$1"
}

set -e

# Parse args
while (( $# )) ; do
	case "$1" in
		--arch|-a)
			arch=$2
			case $arch in
				i686|x86_64) ;;
				*)
					echo >&2 "invalid arch: $arch"
					exit 1
					;;
			esac
			shift
			;;
		init)
			echo 'making a new base image...'

			[[ -e "$image.$arch.qcow2" ]] && mv -f "$image.$arch.qcow2" "$image.$arch.qcow2.bak"

			qemu-img create -f qcow2 "$image.$arch.qcow2" 15G

			echo "arch: $arch"
			connect_nbd "$image.$arch.qcow2"
			mkfs.ext4 "$nbd"
			track_mount "$nbd" "$chroot"


			case $arch in
				x86_64)
					# Strap
					echo 'strapping...'
					pacstrap -d "$chroot" "${base_packages[@]}"

					# Multilib
					echo 'modifying pacman.conf...'
					cat >> "$chroot/etc/pacman.conf" <<-EOF
					[multilib]
					Include = /etc/pacman.d/mirrorlist
					EOF
					;;
				i686)
					sed -e 's/\$arch/i686/g' /etc/pacman.d/mirrorlist > "$chroot/mirrorlist"
					sed -e "s|/etc/pacman.d/mirrorlist|$chroot/mirrorlist|g" \
					    -e '/Architecture/s|auto|i686|' \
					    -e '/\[multilib\]/,/Include/d' \
						/etc/pacman.conf \
					    > "$chroot/pacman.conf"

					mkdir -p "$chroot"/var/{cache/pacman/pkg,lib/pacman}

					pacman --root "$chroot" --cachedir "$chroot/var/cache/pacman/pkg" \
					  --noconfirm --config "$chroot/pacman.conf" -Sy "${base_packages[@]}"
					;;
			esac

			arch-chroot "$chroot" pacman-key --init
			arch-chroot "$chroot" pacman-key --populate

			# Mirrorlist
			echo 'copying mirrorlist...'
			cp -f /etc/pacman.d/mirrorlist "$chroot/etc/pacman.d/mirrorlist"

			# User
			echo 'adding user...'
			arch-chroot "$chroot" groupadd test
			arch-chroot "$chroot" useradd -s /bin/zsh -g test -m test
			arch-chroot "$chroot" echo test:a \| chpasswd

			# Sudo
			echo 'modifying sudoers...'
			sed -i '/root ALL/a\test ALL=NOPASSWD: ALL' "$chroot/etc/sudoers"

			clear_mounts

			qemu-img snapshot -c base "$image.$arch.qcow2"
			;;

		snaps)
			qemu-img snapshot -l "$image.$arch.qcow2"
			;;

		clean)
			echo 'reverting to base snapshot...'
			qemu-img snapshot -a base "$image.$arch.qcow2"

			echo >&2 'cleaning snapshots...'
			qemu-img snapshot -l "$image.$arch.qcow2" | awk '{ print $2 }' |
			sed 1,2d | grep -v '^base$' |
			xargs -n1 -I{} qemu-img snapshot -d {} "$image.$arch.qcow2"
			;;

		revert)
			echo 'reverting to base snapshot...'
			qemu-img snapshot -a base "$image.$arch.qcow2"
			;;

		enter)
			echo 'diving into chroot...'

			connect_nbd "$image.$arch.qcow2"
			track_mount "$nbd" "$chroot"

			if mountpoint -q "$chroot/proc" ; then
				echo 'already mounted.'
				chroot "$chroot" su - test
			else
				echo 'mounting...'

				track_mount "$chroot" "$chroot" --rbind
				track_mount "$blackarch" "$chroot/home/test/blackarch" --bind
				arch-chroot "$chroot" su - test
			fi

			clear_mounts

			qemu-img snapshot -c build$RANDOM "$image.$arch.qcow2"
			;;

		*)
			echo >&2 'invalid command.'
			exit 1
			;;
	esac
	shift
done
